<script setup lang="ts">
import {
  addPatient,
  delPatient,
  editPatient,
  getPatientList
} from '@/services/user'
import { useConsultStore } from '@/stores'
import type { Patient, PatientList } from '@/types/user'
import { idCardRules, nameRules } from '@/utils/rules'
import {
  showConfirmDialog,
  showSuccessToast,
  showToast,
  type FormInstance
} from 'vant'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 1. 页面初始化加载数据
const list = ref<PatientList>([])
const loadList = async () => {
  const res = await getPatientList()
  list.value = res.data

  // 设置默认选中的ID，当你是选择患者的时候，且有患者信息的时候
  if (isChange.value && list.value.length) {
    const defPatient = list.value.find((item) => item.defaultFlag === 1)
    if (defPatient) {
      patientId.value = defPatient.id
    } else {
      patientId.value = list.value[0].id
    }
  }
}
onMounted(() => loadList())

const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]

// 2. 打开侧滑栏
const show = ref(false)
const showPopup = (item?: Patient) => {
  if (item) {
    const { id, gender, name, idCard, defaultFlag } = item
    patient.value = { id, gender, name, idCard, defaultFlag }
  } else {
    patient.value = { ...initPatient } // 重置表单
  }
  show.value = true
}

// 3. 绑定表单
const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}
const patient = ref<Patient>({ ...initPatient })

// 默认值需要转换
const defaultFlag = computed({
  get() {
    return patient.value.defaultFlag === 1 ? true : false
  },
  set(value) {
    patient.value.defaultFlag = value ? 1 : 0
  }
})

// 4. 提交
const form = ref<FormInstance>()
const onSubmit = async () => {
  await form.value?.validate()
  // 身份证倒数第二位，单数是男，双数是女
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗？'
    })
  }

  // 添加 & 修改
  patient.value.id
    ? await editPatient(patient.value)
    : await addPatient(patient.value)
  show.value = false
  loadList()
  showSuccessToast('添加成功')
}

// 5. 删除
const remove = async () => {
  if (patient.value.id) {
    await showConfirmDialog({
      title: '温馨提示',
      message: `您确认要删除 ${patient.value.name} 患者信息吗 ？`
    })
    await delPatient(patient.value.id)
    show.value = false
    loadList()
    showSuccessToast('删除成功')
  }
}

// 选择患者-家庭档案兼容
const route = useRoute()
const isChange = computed(() => route.query.isChange === '1')

// 点击选中效果
const patientId = ref<string>()
const selectedPatient = (item: Patient) => {
  // 仅在 “选择患者” 才显示选中效果
  if (isChange.value) {
    patientId.value = item.id
  }
}

// 下一步
const store = useConsultStore()
const router = useRouter()
const next = () => {
  if (!patientId.value) return showToast('请选择就诊患者')
  store.setPatient(patientId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <!-- 导航组件 -->
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'" />
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <!-- 列表项 -->
    <div class="patient-list">
      <!-- 列表项 -->
      <div
        :class="{ 'patient-item': true, selected: patientId === item.id }"
        @click="selectedPatient(item)"
        v-for="item in list"
        :key="item.id"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">
            {{ item.idCard.replace(/^(.{6}).+(.{4})$/, '\$1********\$2') }}
          </span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon" @click="showPopup(item)">
          <cp-icon name="user-edit" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <!-- 添加患者 -->
      <div class="patient-add" v-if="list.length < 6" @click="showPopup()">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <!-- 提示文本 -->
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>

    <!-- 侧边栏 -->
    <van-popup v-model:show="show" position="right">
      <cp-nav-bar
        :title="patient.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        :back="() => (show = false)"
        @click-right="onSubmit"
      />
      <van-form autocomplete="off" ref="form">
        <van-field
          v-model="patient.name"
          label="真实姓名"
          placeholder="请输入真实姓名"
          :rules="nameRules"
        />
        <van-field
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
          :rules="idCardRules"
        />
        <van-field label="性别" class="pb4">
          <template #input>
            <cp-radio-btn :options="options" v-model="patient.gender" />
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="patient.id">
        <van-action-bar-button @click="remove">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  .patient-list {
    padding: 15px;
    .patient-item {
      position: relative;
      display: flex;
      align-items: center;
      background-color: var(--cp-bg);
      border: 1px solid var(--cp-bg);
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 15px;
      transition: all 0.3s; // 激活时添加类名效果
      .info {
        display: flex;
        flex-wrap: wrap;
        flex: 1;
        span {
          color: var(--cp-tip);
          margin-right: 20px;
          line-height: 30px;
          &.name {
            font-size: 16px;
            color: var(--cp-text1);
            width: 80px;
            margin-right: 0;
          }
          &.id {
            color: var(--cp-text2);
            width: 180px;
            margin-right: 0;
          }
        }
      }
      .icon {
        width: 20px;
        color: var(--cp-text2);
        text-align: center;
      }
      .tag {
        position: absolute;
        top: 21px;
        right: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 16px;
        background-color: var(--cp-primary);
        color: #fff;
        font-size: 10px;
        border-radius: 2px;
      }
      &.selected {
        background-color: var(--cp-plain);
        border-color: var(--cp-primary);
        .cp-icon {
          color: var(--cp-primary);
        }
      }
    }
    .patient-add {
      padding: 15px 0;
      background-color: var(--cp-bg);
      color: var(--cp-primary);
      border-radius: 8px;
      text-align: center;
      .cp-icon {
        font-size: 24px;
      }
    }
    .patient-tip {
      color: var(--cp-tag);
      padding: 12px 0;
    }
  }
  .pb4 {
    padding-bottom: 4px;
  }

  :deep() {
    .van-popup {
      width: 80%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
    .van-action-bar {
      padding: 0 10px;
      margin-bottom: 10px;
      .van-button {
        color: var(--cp-price);
        background-color: var(--cp-bg);
      }
    }
  }

  // 兼容 “选择患者”
  .patient-change {
    padding: 15px;
    > h3 {
      font-weight: normal;
      margin-bottom: 5px;
    }
    > p {
      color: var(--cp-text3);
    }
  }
  .patient-next {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 80px;
    padding: 15px;
    background-color: #fff;
    box-sizing: border-box;
  }
}
</style>
